#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time    : 21-3-9 下午4:44
# @Author  : zgd
# @Site    : 
# @File    : manager.py
# @Software: PyCharm
from datetime import datetime,timedelta
from random import randint

from flask import current_app
from flask import jsonify
from flask_script import Manager
from flask_migrate import Migrate,MigrateCommand

#让整个应用程序知道models存在
from info import create_app,db,models

# 调用方法获取app
from info.models import User
from info.utils.response_code import RET

app = create_app("develop")


manager = Manager(app)

Migrate(app,db)

manager.add_command('db',MigrateCommand)


# 创建管理员对象
# @manager.option()
@manager.option('-u', '--username', dest='username')
@manager.option('-p', '--password', dest='password')

def create_superuser(username,password):
    #1.创建用户对象
    admin = User()

    #2.设置用户属性
    admin.nick_name = username
    admin.mobile = username
    admin.password = password
    admin.is_admin = True

    #3.保存到数据库
    try:
        db.session.add(admin)
        db.session.commit()
    except Exception as e:
        current_app.logger.error(e)
        return "创建失败"
    return "创建成功"


# 添加测试用户
@manager.option('-t', '--test', dest='test')
def add_test_user(test):
    #定义容器

    user_list = []

    #循环创建用户１０００
    for i in range(0,999):
        user = User()
        user.nick_name = "老王%s"%i
        user.mobile = "138%08d"%i
        user.password_hash="pbkdf2:sha256:150000$k8HfPcau$7621e0b538fd89386ead1e9051a4e73656ac89941fe48ecb46334814f4f20b9d"
        # 用户登陆时间为近３１天
        # user.last_login = 今天时间　－ 31随机时间
        user.last_login = datetime.now() -timedelta(seconds=randint(0,31*24*3600))
        user_list.append(user)
        #用户添加到数据库
    try:
        db.session.add_all(user_list)
        db.session.commit()
    except Exception as e:
        current_app.logger.error(e)
        return "添加用户失败"
    return "添加用户成功"

if __name__ == '__main__':
    manager.run()




